package com.sinosoft.taxbenefit.core.Insuredpay.biz.service.impl;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.ws.BindingProvider;
import javax.xml.ws.Holder;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.sinosoft.platform.base.TaxBaseService;
import com.sinosoft.platform.common.util.StringUtil;
import com.sinosoft.taxbenefit.api.base.EBResultCodeDTO;
import com.sinosoft.taxbenefit.api.base.HXResultCodeDTO;
import com.sinosoft.taxbenefit.api.config.ENUM_BZ_RESPONSE_RESULT;
import com.sinosoft.taxbenefit.api.config.ENUM_SENDSERVICE_CODE;
import com.sinosoft.taxbenefit.api.dto.request.base.ParamHeadDTO;
import com.sinosoft.taxbenefit.api.dto.request.base.ThirdSendResponseDTO;
import com.sinosoft.taxbenefit.api.dto.request.customer.ReqInsuredPayInfoDTO;
import com.sinosoft.taxbenefit.api.dto.response.customer.InsuredPayResultDTO;
import com.sinosoft.taxbenefit.core.Insuredpay.biz.service.InsuredPayService;
import com.sinosoft.taxbenefit.core.Insuredpay.dto.InsuredPayClientDTO;
import com.sinosoft.taxbenefit.core.Insuredpay.dto.InsuredPayDTO;
import com.sinosoft.taxbenefit.core.Insuredpay.dto.ReqInsuredPayDTO;
import com.sinosoft.taxbenefit.core.Insuredpay.dto.ResInsuredPayDTO;
import com.sinosoft.taxbenefit.core.common.biz.service.CommonCodeService;
import com.sinosoft.taxbenefit.core.common.config.ENUM_RESULT_CODE;
import com.sinosoft.taxbenefit.core.common.config.ENUM_EBAO_SERVICE_PORT_CODE;
import com.sinosoft.taxbenefit.core.common.config.ENUUM_CODE_MAPPING;
import com.sinosoft.taxbenefit.core.common.dto.EbaoServerPortDTO;
import com.sinosoft.taxbenefit.core.common.dto.SendLogDTO;
import com.sinosoft.taxbenefit.core.common.dto.ThirdSendDTO;
import com.sinosoft.taxbenefit.core.ebaowebservice.CustomerTaxBalanceVerifyService;
import com.sinosoft.taxbenefit.core.ebaowebservice.CustomerTaxBalanceVerifyService_Service;
import com.sinosoft.taxbenefit.core.ebaowebservice.ResponseBody;
import com.sinosoft.taxbenefit.core.ebaowebservice.ResponseHeader;
import com.sinosoft.taxbenefit.core.ebaowebservice.ResponseJSON;
import com.sinosoft.taxbenefit.core.faultTask.biz.service.FaultTaskService;
import com.sinosoft.taxbenefit.core.generated.mapper.TaxContMapper;
import com.sinosoft.taxbenefit.core.transCode.biz.service.TransCodeService;

/**
 * 被保人既往理赔额具体实现
 * @author zhangyu
 * @date 2016年3月10日 上午9:49:22
 */
@Service
public class InsuredPayServiceImpl extends TaxBaseService implements InsuredPayService{
	@Autowired
	private FaultTaskService faultTaskService;
	@Autowired 
	private TaxContMapper taxContMapper;
	@Autowired
	CommonCodeService commonCodeService;
	@Autowired
	TransCodeService  transCodeService;
	
	@Override
	public ThirdSendResponseDTO addInsuredPayInfo(ReqInsuredPayInfoDTO reqInsuredPayInfoDTO,ParamHeadDTO paramHeadDTO) {
		ThirdSendResponseDTO sendResponse = new ThirdSendResponseDTO();
		try{
			logger.info("被保人既往理赔额（核心请求）JSON 体数据内容："+JSONObject.toJSONString(reqInsuredPayInfoDTO));
			//1.将被保人既往理赔额查询请求dto转换为中保信被保人既往理赔额查询请求dto	
			ReqInsuredPayDTO reqInsuredPayDTO = this.tansforDTO(reqInsuredPayInfoDTO);
			//2.调用中保信接口服务,获得返回结果   存储调用中保信日志表
			ThirdSendDTO thirdSendDTO = commonCodeService.createThirdSend(ENUM_EBAO_SERVICE_PORT_CODE.INSURED_PAY_SEL.code(), paramHeadDTO,reqInsuredPayDTO);
			logger.info("被保人既往理赔额查询（请求中保信）JSON 数据内容："+JSONObject.toJSONString(thirdSendDTO));
			Holder<ResponseHeader> responseHeaderHolder = new Holder<ResponseHeader>();
			Holder<ResponseBody> responseBodyHolder = new Holder<ResponseBody>();
			EbaoServerPortDTO ebaoServerPort = commonCodeService.queryEBaoServerInfoByPortCode(ENUM_EBAO_SERVICE_PORT_CODE.INSURED_PAY_SEL.code());
			String portUrl = ebaoServerPort.getPortUrl();
			URL wsdlLocation = new URL(portUrl);
			CustomerTaxBalanceVerifyService_Service service = new CustomerTaxBalanceVerifyService_Service(wsdlLocation);
			CustomerTaxBalanceVerifyService  servicePort = service.getCustomerTaxBalanceVerifyServicePort();
			BindingProvider bp = (BindingProvider) servicePort;
			bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, portUrl);
			servicePort.taxBalanceVerify(thirdSendDTO.getHead(),  thirdSendDTO.getBody(), responseHeaderHolder, responseBodyHolder);
			
			ResponseHeader responseHeader = responseHeaderHolder.value;
			ResponseBody responseBody = responseBodyHolder.value;
			logger.info("被保人既往理赔额查询（中保信响应）JSON 数据内容："+responseBody.getJsonString());
			// 封装中保信返回报文
			ResponseJSON responseJSON = new ResponseJSON();
			responseJSON.setResponseBody(responseBody);
			responseJSON.setResponseHeader(responseHeader);
			// 封装发送报文日志对象
			SendLogDTO sendLog = new SendLogDTO();
			sendLog.setSerialNo(paramHeadDTO.getSerialNo());
			sendLog.setPortCode(ENUM_EBAO_SERVICE_PORT_CODE.INSURED_PAY_SEL.code());
			sendLog.setRequestContent(JSONObject.toJSONString(thirdSendDTO));
			sendLog.setResponseContent(JSONObject.toJSONString(responseJSON));
			sendLog.setTargetCode(ENUM_SENDSERVICE_CODE.EBAO.code());
			sendLog.setState(ENUM_BZ_RESPONSE_RESULT.SUCCESS.code());
			sendLog.setDescription(ENUM_BZ_RESPONSE_RESULT.SUCCESS.description());
			commonCodeService.addLogSend(sendLog);
			//3.封装返回核心dto;
			if(ENUM_RESULT_CODE.SUCCESS.code().equals(responseHeader.getResultCode())
					|| ENUM_RESULT_CODE.INPUT_LOCALITY_SUCCESS.code().equals(responseHeader.getResultCode())){
				sendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.SUCCESS.code());
				sendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.SUCCESS.description());
			}else{
				sendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.FAIL.code());
				List list = responseHeader.getResultMessage().getMessage();
				if(list != null && list.size() > 0){
					StringBuffer sbStr = new StringBuffer(); 
					for(String mess : responseHeader.getResultMessage().getMessage()){
						sbStr.append(mess).append("|");
					}
					String message = sbStr.substring(0, sbStr.length()-1).toString();
					sendResponse.setResultDesc(message);
				}else{
					sendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.FAIL.description());
				}
			}
			// 数据持久化
			if(!StringUtil.isEmpty(responseBody.getJsonString())){
				ResInsuredPayDTO resInsuredPayDTO = JSONObject.parseObject(responseBody.getJsonString(), ResInsuredPayDTO.class);
				if(null != resInsuredPayDTO.getClientList()){
					List<InsuredPayResultDTO> insuredPayResultList = new ArrayList<InsuredPayResultDTO>();
					List<InsuredPayDTO> insuredPayList = resInsuredPayDTO.getClientList();
					for (InsuredPayDTO insuredPayDTO : insuredPayList) {
						InsuredPayResultDTO insuredPayResultDTO = new InsuredPayResultDTO();
						EBResultCodeDTO eBResultCode = insuredPayDTO.getResult();
						HXResultCodeDTO hxResultCode = new HXResultCodeDTO();
						hxResultCode.setResultCode(eBResultCode.getResultCode());
						String message = "";
						if(null != eBResultCode.getResultMessage()){
							StringBuffer sbStr = new StringBuffer(); 
							for(String mess : eBResultCode.getResultMessage()){
								sbStr.append(mess).append("|");
							}
							message = sbStr.substring(0, sbStr.length()-1).toString();
						}
						hxResultCode.setResultMessage(message);
						insuredPayResultDTO.setResult(hxResultCode);
						insuredPayResultDTO.setBizNo(insuredPayDTO.getBusiNo());
						insuredPayResultDTO.setCustomerNo(insuredPayDTO.getCustomerNo());
						insuredPayResultDTO.setAnnualClaimSa(insuredPayDTO.getAnnualClaimSa());
						insuredPayResultDTO.setInsuranceCoverage(insuredPayDTO.getSa());
						insuredPayResultDTO.setWholeLifeClaimSa(insuredPayDTO.getWholeLifeClaimSa());
						insuredPayResultList.add(insuredPayResultDTO);
					}
					if(insuredPayList.size() == 1){
						sendResponse.setResJson(insuredPayResultList.get(0));
					}else{
						sendResponse.setResJson(insuredPayResultList);
					}
				}else{
					sendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.FAIL.code());
					sendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.FAIL.description());
					sendResponse.setResJson("没有返回数据！");
				}
			}
		}catch(Exception e){
			logger.error("被保人既往理赔额查询失败："+e.getMessage());
			sendResponse.setResJson(e.getMessage());
			sendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.FAIL.code());
			sendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.FAIL.description());
			e.printStackTrace();
		}
		logger.error("被保人既往理赔额后置处理结束!");
		return sendResponse;
	}
	/**
	 * 把核心请求的DTO转换成请求中保信的DTO
	 * @param reqInsuredPayInfoDTO
	 * @return
	 */
	public ReqInsuredPayDTO tansforDTO(ReqInsuredPayInfoDTO reqInsuredPayInfoDTO) {
		ReqInsuredPayDTO reqInsuredPayDTO=new ReqInsuredPayDTO();
		InsuredPayClientDTO insuredPayClientDTO=new InsuredPayClientDTO();
		List<InsuredPayClientDTO> insuredPayClientList=new ArrayList<InsuredPayClientDTO>();
		insuredPayClientDTO.setBusiNo(reqInsuredPayInfoDTO.getBizNo());
		insuredPayClientDTO.setName(reqInsuredPayInfoDTO.getName());
		insuredPayClientDTO.setGender(transCodeService.transCode(ENUUM_CODE_MAPPING.GENDER.code(), reqInsuredPayInfoDTO.getGender()));
		insuredPayClientDTO.setBirthday(reqInsuredPayInfoDTO.getBirthday());
		insuredPayClientDTO.setCertiType(transCodeService.transCode(ENUUM_CODE_MAPPING.CARDTYPE.code(),reqInsuredPayInfoDTO.getCertiType()));
		insuredPayClientDTO.setCertiNo(reqInsuredPayInfoDTO.getCertiNo());
		insuredPayClientDTO.setProposalNo(reqInsuredPayInfoDTO.getProposalNo());
		insuredPayClientDTO.setPolicySource(reqInsuredPayInfoDTO.getPolicySource());
		insuredPayClientList.add(insuredPayClientDTO);
		reqInsuredPayDTO.setClientList(insuredPayClientList);
		return reqInsuredPayDTO;
	}
}